<?php

namespace iBrand\Component\Purchase\Models;

use iBrand\Component\Order\Models\Order;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;

class StockRecord extends Model implements Transformable
{
	use SoftDeletes, TransformableTrait;

	const PURCHASE_STOCK   = 'PURCHASE_STOCK';  //采购进货
	const PURCHASE_RETURNS = 'PURCHASE_RETURNS'; //采购退货
	const TAKE_STOCK       = 'TAKE_STOCK'; //库存盘点
	const STORE_SALES      = 'STORE_SALES'; //门店销售
	const STORE_RETURNS    = 'STORE_RETURNS'; //门店退货
	const STORE_TRANSFER   = 'STORE_TRANSFER'; //库存调拨

	protected $guarded = ['id'];

	protected $appends = ['business_type_text', 'order_no'];

	public function __construct(array $attributes = [])
	{
		parent::__construct($attributes);

		$prefix = config('ibrand.app.database.prefix', 'ibrand_');

		$this->setTable($prefix . 'store_stock_record');
	}

	public function setMetaAttribute($value)
	{
		$this->attributes['meta'] = json_encode($value);
	}

	public function getMetaAttribute($value)
	{
		return json_decode($value, true);
	}

	public function getBusinessTypeTextAttribute()
	{
		$text = '';
		if ($this->type == self::PURCHASE_STOCK) {
			$text = '采购进货';
		}

		if ($this->type == self::PURCHASE_RETURNS) {
			$text = '采购退货';
		}

		if ($this->type == self::TAKE_STOCK) {
			$text = '库存盘点';
		}

		if ($this->type == self::STORE_SALES) {
			$text = '门店销售';
		}

		if ($this->type == self::STORE_TRANSFER) {
			$text = '库存调拨';
		}

		return $text;
	}

	public function getOrderNoAttribute()
	{

		$model = new $this->business_type;

		$item = $model::find($this->business_type_id);
		if ($item instanceof Purchase) {
			return $item->code;
		}

		if ($item instanceof TakeStock) {
			return $item->code;
		}

		if ($item instanceof Order) {
			return $item->order_no;
		}

		if ($item instanceof Transfer) {
			return $item->code;
		}

		return '';
	}
}